package com.ruoyi.recruit.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recruit.domain.RecruitContent;
import com.ruoyi.recruit.domain.RecruitUser;
import com.ruoyi.recruit.mapper.RecruitContentMapper;
import com.ruoyi.recruit.mapper.RecruitUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.recruit.mapper.RecruitUserConfirmMapper;
import com.ruoyi.recruit.domain.RecruitUserConfirm;
import com.ruoyi.recruit.service.IRecruitUserConfirmService;
import com.ruoyi.common.core.text.Convert;

/**
 * 到岗人员Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-05-05
 */
@Service
public class RecruitUserConfirmServiceImpl extends ServiceImpl<RecruitUserConfirmMapper, RecruitUserConfirm> implements IRecruitUserConfirmService
{

    @Autowired
    private RecruitContentMapper recruitContentMapper;

    @Autowired
    private RecruitUserMapper recruitUserMapper;

    /**
     * 查询到岗人员
     * 
     * @param id 到岗人员主键
     * @return 到岗人员
     */
    @Override
    public RecruitUserConfirm selectRecruitUserConfirmById(Long id)
    {
        return baseMapper.selectRecruitUserConfirmById(id);
    }

    /**
     * 查询到岗人员列表
     * 
     * @param recruitUserConfirm 到岗人员
     * @return 到岗人员
     */
    @Override
    public List<RecruitUserConfirm> selectRecruitUserConfirmList(RecruitUserConfirm recruitUserConfirm)
    {
        List<RecruitUserConfirm> userConfirmList = baseMapper.selectRecruitUserConfirmList(recruitUserConfirm);
        for(RecruitUserConfirm user : userConfirmList){
            String confirmTime = user.getConfirmTime();
            SimpleDateFormat sdf1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            try {
                Date confirm = sdf1.parse(confirmTime);
                confirmTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, confirm);
            } catch (ParseException e) {
            }
            user.setConfirmTime(confirmTime);
        }
        return userConfirmList;
    }

    /**
     * 新增到岗人员
     * 
     * @param recruitUserConfirm 到岗人员
     * @return 结果
     */
    @Override
    public int insertRecruitUserConfirm(RecruitUserConfirm recruitUserConfirm)
    {
        recruitUserConfirm.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recruitUserConfirm);
    }

    /**
     * 修改到岗人员
     * 
     * @param recruitUserConfirm 到岗人员
     * @return 结果
     */
    @Override
    public int updateRecruitUserConfirm(RecruitUserConfirm recruitUserConfirm)
    {
        recruitUserConfirm.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recruitUserConfirm);
    }

    /**
     * 批量删除到岗人员
     * 
     * @param ids 需要删除的到岗人员主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserConfirmByIds(String ids)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(ids)));
    }

    /**
     * 删除到岗人员信息
     * 
     * @param id 到岗人员主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserConfirmById(Long id)
    {
        return baseMapper.deleteById(id);
    }

    /**
     * 导入到岗人员
     *
     * @param userConfirmList 到岗人员列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUserConfirm(List<RecruitUserConfirm> userConfirmList, Long recruitId, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userConfirmList) || userConfirmList.size() == 0)
        {
            throw new ServiceException("导入到岗人员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecruitUserConfirm userConfirm : userConfirmList)
        {
            int row = 1;
            try
            {
                userConfirm.setRecruitId(recruitId);
                // 获取招聘计划
                RecruitContent recruitContent = recruitContentMapper.selectOne(new LambdaQueryWrapper<RecruitContent>()
                        .eq(RecruitContent::getPostCode, userConfirm.getPostCode())
                        .eq(RecruitContent::getPostName, userConfirm.getPostName())
                        .eq(RecruitContent::getRecruitId, recruitId).last("limit 1"));
                if(StringUtils.isNull(recruitContent)){
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行招聘计划不存在");
                    continue;
                }
                userConfirm.setContentId(recruitContent.getContentId());
                // 获取应聘人员信息
                RecruitUser recruitUser = recruitUserMapper.selectOne(new LambdaQueryWrapper<RecruitUser>()
                        .eq(RecruitUser::getIdCard, userConfirm.getIdCard())
                        .eq(RecruitUser::getContentId, recruitContent.getContentId()).last("limit 1"));
                if (StringUtils.isNull(recruitUser))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行应聘人员不存在");
                    continue;
                }
                userConfirm.setUserId(recruitUser.getUserId());
                //查询是否已存在到岗人员信息
                RecruitUserConfirm info = baseMapper.selectOne(new LambdaQueryWrapper<RecruitUserConfirm>()
                        .eq(RecruitUserConfirm::getContentId, recruitContent.getContentId())
                        .eq(RecruitUserConfirm::getUserId, userConfirm.getUserId()).last("limit 1"));
                if(StringUtils.isNull(info)){
                    userConfirm.setCreateBy(operName);
                    this.insertRecruitUserConfirm(userConfirm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行到岗人员信息导入成功");
                }else if(isUpdateSupport){
                    userConfirm.setId(info.getId());
                    userConfirm.setUpdateBy(operName);
                    this.updateRecruitUserConfirm(userConfirm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行到岗人员信息更新成功");
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行到岗人员信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行到岗人员信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            row++;
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
